<template>
  <div class="sticky" :style="getPosition">
    <div class="sticky-warp">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    getPosition() {
      let position = this.cssSupport('position', 'sticky') ? 'sticky' : 'relative';
      return 'position:' + position;
    }
  },
  mounted() {
    this.init();
  },
  deactivated() {
    if (this.cssSupport('position', 'sticky')) {
      return;
    }

    // 复位
    let elWarp = this.$el.querySelector('.sticky-warp');
    elWarp.position = 'absolute';
  },
  methods: {
    init() {
      if (this.cssSupport('position', 'sticky')) {
        return;
      }

      let el = this.$el;
      let target = this.$el.parentNode;
      let elWarp = this.$el.querySelector('.sticky-warp');
      let top = this.getNumberValue(document.defaultView.getComputedStyle(el).top);

      this.addScrollListen(target, () => {
        if (el.getBoundingClientRect().top <= top) {
          elWarp.style.position = 'fixed';
        }

        if (el.getBoundingClientRect().top >= 0 && elWarp.style.position != 'absolute') {
          elWarp.style.position = 'absolute';
        }
      });
    },
    cssSupport(attr, value) {
      let element = document.createElement('div');

      if (attr in element.style) {
        element.style[attr] = value;
        return element.style[attr] === value;
      } else {
        return false;
      }
    },
    getNumberValue(pxValue) {
      let value = String(pxValue).match(/^\-?\+?[0-9]+/g);
      return value ? Number(value) : undefined;
    },
    addScrollListen(target, cb) {
      target.addEventListener('y-scroll', (event) => {
        cb && cb(event);
      });
    }
  },
}
</script>

<style>
.sticky {
  width: 100%;
}

.sticky .sticky-warp {
  width: 100%;
  background: inherit;
  will-change: change;
  height: inherit;
  top: inherit;
}
</style>
